package rpc;

import com.rabbitmq.client.*;
import constant.Constants;

import java.io.IOException;
import java.util.UUID;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeoutException;

public class Client {
    public static void main(String[] args) throws IOException, TimeoutException, InterruptedException {
        // 创建连接工厂
        ConnectionFactory factory = new ConnectionFactory();
        // 设置IP地址、端口号
        factory.setHost(Constants.HOST);
        factory.setPort(Constants.PORT);
        // 设置虚拟机名称
        factory.setVirtualHost(Constants.VIRTUAL_HOST);
        // 设置用户名和密码
        factory.setUsername(Constants.USER_NAME);
        factory.setPassword(Constants.USER_PASSWORD);
        // 创建连接
        Connection connection = factory.newConnection();
        // 创建 channel
        Channel channel = connection.createChannel();
        // 使用默认的交换机
        // 声明队列
        channel.queueDeclare(Constants.RPC_QUEUE_1, true, false, false, null);
        channel.queueDeclare(Constants.RPC_QUEUE_2, true, false, false, null);
        // 本次请求的唯一标识
        String corrId = UUID.randomUUID().toString();
        // 发送消息
        String message = "hello rpc...";
        /**
         * String exchange,
         * String routingKey,
         * BasicProperties props,
         * byte[] body
         */
        // 消息属性
        AMQP.BasicProperties basicProperties = new AMQP.BasicProperties()
                .builder()
                .correlationId(corrId) // 唯一ID
                .replyTo(Constants.RPC_QUEUE_2) // 回调队列
                .build();
        channel.basicPublish("", Constants.RPC_QUEUE_1, basicProperties, message.getBytes());
        // 阻塞队列，用于存放回调结果，一次获取一条消息
        BlockingQueue<String> queue = new ArrayBlockingQueue<>(1);
        // 接收服务器的响应
        DefaultConsumer consumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println("接收到回调消息: " + new String(body));
                // 判断标识是否正确
                if(corrId.equals(properties.getCorrelationId())) {
                    queue.offer(new String(body, "UTF-8"));
                }
            }
        };
        channel.basicConsume(Constants.RPC_QUEUE_2, true, consumer);
        // 获取到回调结果
        while (!queue.isEmpty()) {
            String result = queue.take();
            System.out.println("result: " + result);
        }
    }
}
